// pages/find/add/add.js
const T = require('../../../utils/tool.js')
const config = require('../../../config.js')
let token = ''
let userHrId = ''
import {
  $wuxSelect
} from '../../../wux-components/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    fileList: [],
    uploadUrl: config.host + 'admin/file/singleFile?token=' + token,
    formData: {
      type: 'image'
    },
    plateName: '请选择',
    plateId: -1,
    isPublishAct: false,
    actItemMax: 8,
    actList: [],
    typeText: {},
    postTitle: '',
    postContent: '',
    activityName: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    token = getApp().globalData.token;
    userHrId = getApp().globalData.userId;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  toast(text, type) {
    T.toast({
      id: '#wux-toast',
      text: text,
      success: () => { }
    })
  },

  /**
   * 标题
   */
  onInputTitle(e) {
    this.setData({
      postTitle: e.detail.value,
    })
  },

  /**
   *内容 
   */
  onInputContent(e) {
    this.setData({
      postContent: e.detail.value,
    })
  },

  /**
   * 活动名称
   */
  onActtName(e) {
    this.setData({
      activityName: e.detail.value
    });
  },

  onUploadSuccess(e) {
    console.log(e);
    this.setData({
      fileList: e.detail.fileList.map((n) => {
        // 如果上传失败显示红框
        if (n.status == 'error') {
          return n
        }
        let _resData = JSON.parse(n.res.data);
        if (_resData.code != 200) {
          return Object.assign(n, {
            status: 'error'
          });
        } else {
          return Object.assign(n, {
            status: 'success'
          });
        }
      })
    })
  },

  /**
   * 移除上传失败的图片
   */
  onRemoveImg(e) {
    this.data.fileList.splice(e.detail.index, 1);
  },

  onUploadFail(e) {
    console.log(e)
  },

  /**
   * 选择板块
   */
  onSelectPlate() {
    wx.navigateTo({
      url: '../plate-list/list',
    })
  },

  onPublishAct(e) {
    this.setData({
      isPublishAct: !this.data.isPublishAct
    })
  },

  onAddActItem() {
    console.log();
    if (this.data.actList.length == this.data.actItemMax) {
      this.toast('仅能添加8个项目');
      return;
    }
    $wuxSelect('#wux-select-type').open({
      value: '',
      toolbar: {
        title: '请选择项目类型',
        confirmText: '确定',
        cancelText: '取消'
      },
      options: [{
        'title': '数字',
        value: 0
      },
      {
        'title': '电话',
        value: 1
      },
      {
        'title': '邮箱',
        value: 2
      },
      {
        'title': '文本',
        value: 3
      }
      ],
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.data.actList.push({
            value: '',
            title: options[index].title,
            type: value,
            textType: value == 0 ? 'digit' : (value == 1 ? 'number' : (value == 2 ? 'text' : 'text')),
            isError: false
          });
          this.setData({
            actList: this.data.actList,
          });
        }
      }
    });
  },

  // 记录项目输入值 
  onActItem(e) {
    const _index = e.currentTarget.dataset.tag;
    const _type = e.currentTarget.dataset.type;
    const _value = e.detail.value;
    // 去除错误提示
    if (!_value) {
      const key = 'actList[' + _index + '].isError';
      this.setData({
        [key]: false
      });
      return;
    }
    // 判断是否输入值与类型有误
    // this.isInputError(_index, _type, _value);
    let _obj = Object.assign(this.data.actList[_index], { value: _value, type: _type });
    this.data.actList.splice(_index, 1, _obj);
  },

  /**
   * 输入实时检验
   */
  isInputError(_i, _t, _v) {
    let key = 'actList[' + _i + '].isError';
    // 电话
    if (_t == 1 && !T.regExp.tel.test(_v)) {
      this.setData({
        [key]: true
      });
      return;
    } else {
      this.setData({
        [key]: false
      });
    }

    // 邮箱
    if (_t == 2 && !T.regExp.email.test(_v)) {
      this.setData({
        [key]: true
      });
      return;
    } else {
      this.setData({
        [key]: false
      });
    }
    let _obj = Object.assign(this.data.actList[_i], { value: _v, type: _t });
    this.data.actList.splice(_i, 1, _obj);
  },

  /**
   * 最后提交时检验
   */
  isAllInputError() {
    const _temArr = this.data.actList;
    console.log(_temArr)
    let isError = false;
    _temArr.forEach((ele, i) => {
      if (ele.type == 0 && !ele.value) {
        // 数字
        this.setData({
          ['actList[' + i + '].isError']: true,
        });
        isError = true;
      }
      if (ele.type == 3 && !ele.value) {
        // 文本
        this.setData({
          ['actList[' + i + '].isError']: true,
        });
        isError = true;
      }
      // 手机 或者 邮箱
      if (ele.type == 1 || ele.type == 2) {
        if (!ele.value) {
          this.setData({
            ['actList[' + i + '].isError']: true,
          });
          isError = true;
        }
      }
    })
    return isError;
  },

  onDelActItem(e) {
    const _index = e.currentTarget.dataset.tag;
    const _arr = this.data.actList.slice(0);
    _arr.splice(_index, 1);
    this.setData({
      actList: _arr
    })
  },

  onActName(e) {
    this.setData({ activityName: e.detail.value });
  },

  // 发布帖子
  onPublishPost() {
    let title = this.data.postTitle,
      content = this.data.postContent,
      fileList = this.data.fileList,
      haveActivity = this.data.isPublishAct ? 1 : 0,
      itemName = this.data.activityName,
      modelId = this.data.plateId,
      itemList = this.data.actList;

    if (!title) {
      this.toast('请输入标题');
      return;
    }
    if (!content) {
      this.toast('请输入内容');
      return;
    }
    if (modelId == -1) {
      this.toast('请选择板块');
      return;
    }


    if (this.data.isPublishAct) {
      if (!itemName) {
        this.toast('请输入活动名称');
        return;
      }
      let isError = this.isAllInputError();
      if (isError) {
        this.toast('输入有误,请检查');
        return;
      }
    }

    let topic = {};
    let isUploadFail = false;
    let photoIndex = 0;
    fileList.forEach((ele, i) => {
      let _resData = JSON.parse(ele.res.data);
      photoIndex = (i + 1);
      if (!_resData.err) {
        topic['photo' + (i + 1)] = _resData.data.url;
      } else {
        isUploadFail = true;
      }
    });
    photoIndex = photoIndex == 0 ? 0 : photoIndex;
    for (let i = photoIndex + 1; i < 10; i++) {
      topic['photo' + i] = '';
    }
    if (isUploadFail) {
      this.toast('有某张图片上传失败,请重新上传');
      return;
    }
    topic.modelId = modelId;
    topic.title = title;
    topic.content = content;
    topic.userHrId = userHrId;
    topic.haveActivity = haveActivity;

    let activity = {
      itemName: itemName,
      itemList: []
    };

    itemList.forEach((ele, i) => {
      activity.itemList.push({
        item: ele.value,
        type: Number(ele.type)
      })
    });

    T.req({
      url: config.api + 'forum/topic?token=' + token,
      method: 'POST',
      data: {
        topic: topic,
        activity: activity
      },
      success: (res) => {
        T.toast({
          id: '#wux-toast',
          text: '发布成功',
          type: 'success',
          success: () => {
            let param = {
              id: modelId,
              name: this.data.plateName
            }
            wx.navigateTo({
              url: '../list/list?' + T.param(param),
            })
          }
        })
      }
    });
  }
})